<template>
  <!-- 顶部背景及内容区域 -->
  <div class="top-bak">
    <h1 class="title">一方天地</h1>
    <p class="subtitle">当你点开这页，便踏入了用诗句铺就的小径，每一步都踩着生活的平仄，在喧嚣之外，寻得片刻诗意的栖居</p>
    <p class="author">猫盹的日影、瓶敛的残阳、夜悬的星钟，妥帖收存</p>
  </div>
  <div class="add-btn">
    <svg t="1753019053066" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
         @click="showFriendCycleModel" p-id="5243" width="200" height="200">
      <path
          d="M512 909.061224c-218.906122 0-397.061224-178.155102-397.061224-397.061224s178.155102-397.061224 397.061224-397.061224 397.061224 178.155102 397.061224 397.061224-178.155102 397.061224-397.061224 397.061224z"
          p-id="5244"></path>
      <path
          d="M660.897959 531.853061h-297.795918c-10.971429 0-19.853061-8.881633-19.853061-19.853061s8.881633-19.853061 19.853061-19.853061h297.795918c10.971429 0 19.853061 8.881633 19.853061 19.853061s-8.881633 19.853061-19.853061 19.853061z"
          fill="#DCFFFA" p-id="5245"></path>
      <path
          d="M512 680.75102c-10.971429 0-19.853061-8.881633-19.853061-19.853061v-297.795918c0-10.971429 8.881633-19.853061 19.853061-19.853061s19.853061 8.881633 19.853061 19.853061v297.795918c0 10.971429-8.881633 19.853061-19.853061 19.853061z"
          fill="#DCFFFA" p-id="5246"></path>
    </svg>
  </div>

  <a-modal v-model:open="open1" title="发表朋友圈">
    <template #footer>
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button key="submit" type="primary" :loading="loading" @click="saveFriendCycle">发表</a-button>
    </template>
    <a-textarea v-model:value="addFriendCycleForm.content" :rows="5" placeholder="请输入你的想法..."
                style="margin-bottom: 20px;"/>
    <!-- 图片上传区域 -->
    <a-upload v-model:file-list="fileList" list-type="picture-card" :customRequest="uploadImages"
              @preview="handlePreview">
      <div v-if="fileList.length < 8">
        <PlusOutlined/>
      </div>
    </a-upload>
    <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
      <img style="width: 100%" :src="previewImage"/>
    </a-modal>
    <a-select v-model:value="addFriendCycleForm.tagList" mode="tags" style="width: 100%" placeholder="标签"
              :options="tagOptions" @change="handleChange"></a-select>
  </a-modal>

  <!-- 朋友圈时间轴 -->
  <a-spin tip="加载中..." :spinning="spinning">
    <div class="container" v-if="chatItems.length > 0">
      <!-- 时间轴线 -->
      <div class="timeline-line"></div>
      <!-- 聊天内容项 -->
      <div v-for="(item, index) in chatItems" :key="index" class="timeline-item"
           :class="item.position === 'left' ? 'timeline-item-left' : 'timeline-item-right'">
        <div class="timeline-dot">
          <a-avatar :class="item.position === 'left' ? 'left-avatar' : 'right-avatar'" style="position: absolute;"
                    :src="item.avatar">
          </a-avatar>
        </div>
        <div class="timeline-content">
          <p class="content" v-html="item.content"></p>
          <div class="image" v-if="item.imgList && item.imgList.length > 0">
            <a-image-preview-group>
              <a-image :width="190" v-for="img in item.imgList" :key="img.id" :src="img.url"/>
            </a-image-preview-group>
          </div>
          <div style="display: flex;align-items: center;justify-content: space-between;margin-top: 10px;">
            <span class="time">{{ item.createTime }}</span>
            <span v-if="item.tag" class="time-badge">{{ item.tag }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="empty-content" v-else>空空如也~~</div>
    <div class="more" v-if="chatItems.length > 0">
      <a-button v-if="hasMore" type="primary" @click="getFriendCyclePage">加载更多</a-button>
      <div v-else class="bottom-txt">
        <svg t="1752583245913" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
             p-id="2598" width="200" height="200">
          <path d="M992 96v768l-308.16-176L480 928l-128-448-320-128 960-256z" fill="#548AFF" p-id="2599"></path>
          <path d="M992 96L544 608l-64 320-128-448L992 96z" fill="#4367E0" p-id="2600"></path>
          <path d="M683.84 688L480 928l64-320 139.84 80z" fill="#2744C1" p-id="2601"></path>
        </svg>
      </div>
    </div>
  </a-spin>


</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import {addFriendCycle, findFriendCyclePageList} from '@/api/friendCycle';
import {PlusOutlined} from '@ant-design/icons-vue';
import {message} from 'ant-design-vue';
import {upload2} from '@/api/file';
// 状态
const loading = ref(false);
const spinning = ref(false);
// 模块id
const moduleId = '5';
// 弹窗
const open1 = ref(false);
// 朋友圈数据
const chatItems = ref([]);
// 是否有更多数据
const hasMore = ref(false);
// 查询参数
const queryForm = reactive({
  pageModel: {
    pageNow: 1,
    pageSize: 10,
    sort: ['1create_time']
  }
});
const tagOptions = ref([]);
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
// 文件列表
const fileList = ref([]);
const addFriendCycleForm = reactive({
  content: '',
  imgIds: [],
  tagList: [],
});
// 限制最大上传5张图
const maxImages = 5;
// 单张图片最大20MB
const maxSize = 20 * 1024 * 1024;
// 允许的图片类型
const allowTypes = [
  'image/jpeg',   // JPG/JPEG
  'image/png',    // PNG
  'image/webp',   // WebP
  'image/gif',    // GIF（支持动态图）
  'image/bmp',    // BMP
  'image/tiff',   // TIFF
  'image/svg+xml' // SVG（矢量图）
];
// 图片类型友好名称映射（用于错误提示）
const allowedTypeNames = {
  'image/jpeg': 'JPG/JPEG',
  'image/png': 'PNG',
  'image/webp': 'WebP',
  'image/gif': 'GIF',
  'image/bmp': 'BMP',
  'image/tiff': 'TIFF',
  'image/svg+xml': 'SVG'
};
const handleChange = value => {
  console.log(`selected ${value}`);
  if (addFriendCycleForm.tagList.length > 1) {
    addFriendCycleForm.tagList = addFriendCycleForm.tagList[addFriendCycleForm.tagList.length - 1]
  }
};
// 分页获取朋友圈列表
const getFriendCyclePage = async () => {
  spinning.value = true;
  await findFriendCyclePageList(queryForm).then(res => {
    if (res.code === 200) {
      chatItems.value = [...chatItems.value, ...res.data.list.dataList];
      if (res.data.list.total > chatItems.value.length) {
        hasMore.value = true;
        queryForm.pageModel.pageNow++;
      } else {
        hasMore.value = false;
      }
      spinning.value = false;

      // 关键：新数据加载后，重新观察所有元素
      setTimeout(observeTimelineItems, 0); // 延迟确保DOM已更新
    }
  }).catch(error => {
    console.log(error);
    spinning.value = false;
  });
}
// 展示添加朋友圈弹框
const showFriendCycleModel = () => {
  addFriendCycleForm.content = '';
  addFriendCycleForm.imgUrlList = [];
  open1.value = true;
}
// 添加朋友圈
const saveFriendCycle = () => {
  loading.value = true;
  if (!addFriendCycleForm.content && fileList.value.length === 0) {
    message.error('请输入内容或上传图片');
    loading.value = false;
    return;
  }

  addFriendCycle(addFriendCycleForm).then(res => {
    if (res.code === 200) {
      if (chatItems.value.length > 0) {
        res.data.position = chatItems.value[0].position === 'right' ? 'left' : 'right';
      }
      message.success('添加成功');
      chatItems.value = [res.data, ...chatItems.value];
      addFriendCycleForm.content = '';
      addFriendCycleForm.imgIds = [];
      fileList.value = [];
      loading.value = false;
      open1.value = false;

      // 关键：新数据加载后，重新观察所有元素
      setTimeout(observeTimelineItems, 0); // 延迟确保DOM已更新
    }
  }).catch(err => {
    console.log(err);
  })
}
// 取消预览
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
  open1.value = false;
};
// 预览图片
const handlePreview = async file => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};
// 上传图片
const uploadImages = async ({file}) => {
  if (fileList.value.length > maxImages) {
    message.warn(`最多只能上传${maxImages}张图片`);
    return;
  }
  // 校验图片大小
  if (file.size > maxSize) {
    const sizeInMB = (maxSize / (1024 * 1024)).toFixed(1);
    message.warn(`图片大小不能超过${sizeInMB}MB`);
    return;
  }
  // 校验图片类型
  if (!allowTypes.includes(file.type)) {
    const allowedTypesText = allowTypes.map(type => allowedTypeNames[type] || type).join('、');
    message.warn(`请上传${allowedTypesText}格式的图片`);
    return; // 阻止上传
  }
  // 上传文件
  const formData = new FormData();
  formData.append('file', file);
  formData.append('moduleId', moduleId);
  upload2(formData).then(res => {
    const fileInfo = res.data.data;
    if (res.data.code !== 200 || !fileInfo) {
      message.success("上传失败");
    } else {
      message.success("上传成功");
      file.url = fileInfo.fileAddress;
      file.id = fileInfo.id;
      let newFileList = [];
      for (let i = 0; i < fileList.value.length; i++) {
        let one = fileList.value[i];
        if (!one.originFileObj) {
          newFileList.push(one)
        }
      }
      newFileList.push(file);
      fileList.value = [...newFileList];
      addFriendCycleForm.imgIds = [...fileList.value.map(item => item.id)];
    }
  }).catch(err => {
    console.log(err);
  });
};


// 定义全局的观察者变量
const observer = ref(null);

// 初始化观察者（提取为单独函数）
const initObserver = () => {
  observer.value = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('visible');
      }
    });
  }, {threshold: 0.1});
};

// 观察所有timeline-item（包括新添加的）
const observeTimelineItems = () => {
  if (!observer.value) return;

  // 先停止观察已有的元素（避免重复观察）
  document.querySelectorAll('.timeline-item').forEach(item => {
    observer.value.unobserve(item);
  });

  // 重新观察所有元素（包括新添加的）
  document.querySelectorAll('.timeline-item').forEach(item => {
    observer.value.observe(item);
  });
};


// 滚动动画
onMounted(async () => {
  initObserver(); // 初始化观察者
  await getFriendCyclePage();
  observeTimelineItems(); // 观察初始元素
});
</script>

<style scoped>
.left-avatar {
  top: -11px;
  left: -40px;
}

.right-avatar {
  top: -11px;
  left: 20px;
}

.top-bak {
  width: 100%;
  height: 350px;
  background: url('@/assets/img/full-moon-clouds-pink-sky-scenic-aesthetic.jpg') center/cover no-repeat;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
  text-align: center;
  position: relative;
  margin-bottom: 50px;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem;
  position: relative;
}

/* 时间轴样式 */
.timeline-container {
  position: relative;
  min-height: 100%;
  padding-bottom: 2rem;

}

/* 时间轴线 */
.timeline-line {
  position: absolute;
  background: linear-gradient(to bottom, #4F46E5, #EC4899);
  left: 50%;
  transform: translateX(-50%);
  height: 100%;
  top: 0;
  bottom: 0;
  width: 2px;
}


.timeline-item {
  position: relative;
  margin-bottom: 4rem;
  width: 100%;

  &::after {
    content: '';
    display: table;
    clear: both;
  }
}

.timeline-dot {
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 3px solid white;
  z-index: 10;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.timeline-item-left .timeline-dot {
  background-color: #4F46E5;
}

.timeline-item-right .timeline-dot {
  background-color: #EC4899;
}

.timeline-content {
  width: calc(50% - 4rem);
  padding: 1rem;
  border-radius: 8px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  position: relative;
  transition: transform 0.3s ease;
}

.timeline-item-left .timeline-content {
  float: left;
  background-color: rgba(79, 70, 229, 0.05);
  border: 1px solid rgba(79, 70, 229, 0.1);
}

.timeline-item-right .timeline-content {
  float: right;
  background-color: rgba(236, 72, 153, 0.05);
  border: 1px solid rgba(236, 72, 153, 0.1);
}

/* 气泡箭头 */
.timeline-content::before {
  content: '';
  position: absolute;
  top: 12px;
  width: 0;
  height: 0;
  border-style: solid;
}

.timeline-item-left .timeline-content::before {
  right: -12px;
  border-width: 10px 0 10px 12px;
  border-color: transparent transparent transparent rgba(79, 70, 229, 0.05);
}

.timeline-item-right .timeline-content::before {
  left: -12px;
  border-width: 10px 12px 10px 0;
  border-color: transparent rgba(236, 72, 153, 0.05) transparent transparent;
}

.content {
  font-size: 1.1rem;
  margin-bottom: 0.5rem;
}

.time {
  font-size: 0.8rem;
  color: #6b7280;
  display: block;
  text-align: right;
}

.time-badge {
  display: inline-block;
  padding: 0.25rem 0.75rem;
  border-radius: 9999px;
  font-size: 0.75rem;
  font-weight: 500;
}

.timeline-item-left .time-badge {
  color: #4F46E5;
  background-color: rgba(79, 70, 229, 0.1);
}

.timeline-item-right .time-badge {
  color: #EC4899;
  background-color: rgba(236, 72, 153, 0.1);
}

/* 调整最后一个元素的间距，避免线条过短 */
.timeline-item:last-child {
  margin-bottom: 0;
  padding-bottom: 2rem;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .timeline-line {
    left: 13px;
    top: 0;
    bottom: 0;
  }

  .timeline-dot {
    left: -19px;
    top: 15px;
  }

  .timeline-content {
    width: calc(100% - 3.5rem);
    float: right;
  }

  .timeline-item-left .timeline-content,
  .timeline-item-right .timeline-content {
    background-color: rgba(243, 244, 246, 0.8);
    border: 1px solid rgba(229, 231, 235, 0.8);

    &::before {
      left: -12px;
      border-width: 10px 12px 10px 0;
      border-color: transparent rgba(243, 244, 246, 0.8) transparent transparent;
    }
  }

  .timeline-item-left .timeline-content {
    left: 45px;
  }

  .left-avatar {
    left: 17px;
  }

  .timeline-item-right .timeline-content {
    left: -10px;
  }

  .time-badge {
    margin-top: 0.75rem;
  }
}

/* 动画效果 */
.timeline-item {
  opacity: 0;
  transform: translateY(20px);
  transition: opacity 0.6s ease, transform 0.6s ease;
}

.timeline-item.visible {
  opacity: 1;
  transform: translateY(0);
}

.empty-content {
  text-align: center;
  font-size: 20px;
  color: #666;
}

.more {
  margin-top: 20px;
  margin-bottom: 10px;
  color: #666;
  text-align: center;

  @media (max-width: 640px) {
    text-align: left;
  }

  .bottom-txt {
    font-size: 30px;
  }
}

.add-btn {
  text-align: center;
  font-size: 30px;

  @media (max-width: 640px) {
    text-align: left;
  }

  svg {
    cursor: pointer;
    color: #3b82f6;
    transition: 0.1s linear;

    &:hover {
      color: #0e61e8;
    }
  }
}

:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-image) {
  margin: 5px;
}
</style>